<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" class="preview" v-if="avatar" alt="" />
      <img
        src="@/project/staggerer/assets/images/avatar.jpg"
        v-else
        class="preview"
        alt=""
      />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          accept="image/"
          style="display: none"
          ref="iptRef"
          @change="onFileChange"
        />
        <el-button type="primary" @click="chooseImg" icon="el-icon-plus"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="avatar === ''"
          @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import axios from '@/project/staggerer/Dsrc/main.js'
export default {
  name: 'UserAvatar',
  data() {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImg() {
      this.$refs.iptRef.click()
    },
    // 获取用户选择的文件列表 (伪数组)
    onFileChange(e) {
      const files = e.target.files
      if (files.length === 0) {
        // 没有选择图片
        this.avatar = ''
      } else {
        // 创建 fileReader 对象
        const fr = new FileReader()
        // 调用 redAsDateURL 函数读取文件类容
        fr.readAsDataURL(files[0])
        // 监听 fr 的 onload 事件
        fr.onload = e => {
          // 通过 e.target.result 获取到读取的结果 值是字符串 base64 格式的字符串
          this.avatar = e.target.result
        }
      }
    },
    async uploadAvatar() {
      const { data: res } = await axios.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      if (res.code !== 0) return this.$message.error('上传失败')
      this.$message.success('上传成功')
      this.$store.dispatch('Ditem/initUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  width: 350px;
  height: 350px;
  object-fit: cover;
}
// 重置卡片的基础样式
.el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  font-size: 13px;
}
</style>
